/** These are all the data structures.*/
// This holds the data for the Driver accordion fold
function driver_obj(name,desc,comments,active,bypass,schema,datasource,map_name,id,coord)
{
	this.reportName=name;
	this.reportDesc=desc;
	this.driverComments=comments;
	this.driverActive=active;
	this.byPassed=bypass;
	this.reportSchema=schema;
	this.schemaChange=true; // This flag is to indicate whether or not the schema has changed since
							// the last time the list of valid field names has been grabbed from the 
							// database.
	this.reportDS=datasource;
	this.dsChange=true;		// This flag serves the same purpose as the schemaChange flag, except for
							// a change in the datasource.
	this.mapName=map_name;
	this.mapUID=id;
	this.coord_system_name=coord;
}
// This is a single member of the list of links that, when propperly parsed, make up the Link Trail
// at the top of the DBRS window.
function links_list_obj(text,address)
{
	this.link_text=text;
	this.link_address=address;
	this.print=function()
	{
		alert(this.link_text+" <"+this.link_address+">");
	}
}
// This holds the data for the user-interface, part of the data in the REPORT_DRIVER table.
function user_interface_obj(page,header,subHeader,image)
{
	this.interface_page_title=page;
	this.interface_header_title=header;
	this.interface_subHeader_title=subHeader;
	this.interface_image_address=image;
	this.links_list = new Array(); // a list of links_list_obj
}
// This holds the data of a member of the list of fields in the Fields fold.  Each field_obj
// represents one row in the REPORT_FIELDS table in the database.
function field_obj(number,name,dname,desc,sortable,selected,order,type,field_function,value,display)
{
	this.field_number=number;
	this.field_name=name;
	this.field_display_name=dname;
	this.description=desc;
	this.field_sortable=sortable;
	this.default_selected=selected;
	this.field_sort_order=order;
	this.data_type=type;
	this.field_function=field_function;
	this.value_info=value;
	this.display=display;
	this.print=function()
	{
		alert(this.field_number+" "+this.field_name+" "+this.field_display_name+" "+this.description+" "+
				this.field_sortable+" "+this.default_selected+" "+this.field_sort_order+" "+this.data_type+" "+
				this.field_function+" "+this.value_info+" "+this.display);
	}
}
//This holds the data of a member of the list of parameters in the Parameters fold.  Each parameter_obj
//represents one row in the REPORT_PARAMETERS table in the database.
function parameter_obj(number,name,dname,desc,type,required,avalues,dvalues,schema,source_name,field_names,where,order,constrain,validate)
{
	this.parameter_number=number;
	this.parameter_name=name;
	this.parameter_display_name=dname;
	this.parameter_description=desc;
	this.data_type=type;
	this.parameter_required=required;
	this.actual_values=avalues;
	this.display_values=dvalues;
	this.ds_schema=schema;
	this.ds_name=source_name;
	this.ds_field_names=field_names;
	this.where_clause=where;
	this.order_by_clause=order;
	this.constraining_parameter_name=constrain;
	this.validator_name = validate;
	this.print=function()
	{
		alert("number: "+this.parameter_number+"\nname: "+this.parameter_name+"\ndisplay name: "+this.parameter_display_name+"\ndescription: "+this.parameter_description+"\n data type: "+
				this.data_type+"\n required: "+this.parameter_required+"\nactual values: "+this.actual_values+"\ndisplay values: "+this.display_values+"\n schema:"+
				this.ds_schema+"\n datasource name: "+this.ds_name+"\nfield names: "+this.ds_field_names+"\n where clause: "+this.where_clause+"\norder-by clause: "+this.order_by_clause+
				"\n constraining parameter: "+this.constraining_parameter_name+"\n validator name: "+this.validator_name);
	}
}
//This holds the data of a member of the list of security parameters in the Security fold.  Each security_obj
//represents one row in the REPORT_SECURITY table in the database.
function security_obj(restriction,parameters)
{
	this.security_restriction=restriction;
	this.security_parameters=parameters;
}
// This holds the data for a member of the dynamically-created list of fields in a given data source, be
// it table, view, or materialized view.
function ds_field_obj(name,type)
{
	this.name = name; // name of the field
	this.type = type; // Oracle datatype this field is
	this.print=function()
	{
		alert("name: "+this.name+"  type: "+this.type);
	}
}
// These are the instances or the arrays that contain the instances of all of these data structures
// *** Special note about the arrays: the 0 place in them contains the object that is to be worked on ***
// *** 		what this means is that if you want to edit the data in the 3rd parameter_obj,            ***
// ***		parameters[0] would contain the number 3.  This means that the arrays effectively start at***
// ***		1 instead of 0.																			  ***
var driver = new driver_obj();
var user_interface = new user_interface_obj();
var fields=new Array(); //		Array of field_obj
var parameters=new Array();//	Array of parameter_obj
var securitys=new Array();//	Array of security_obj
var category = 0;
var ds_fields=new Array();//	Array of ds_field_obj
/** End 'Data Structures' section*/

//TODO a section marker between data sources and utility functions

/** This section contains utility functions*/
// This function makes sure that all Strings that are sent in are output in a relatively uniform length.
// The strings themselves are not changed.
function maxLength(string,max)
{
	if(string != null && string.length > max)
		return string.substr(0,max);
	else
		return string
}

//This function takes in a variable, a String, and checks to see if it's empty or not, 
//if yes, it return true
function isNull(variable)
{
	if(variable == null || variable == undefined || variable == "" || variable.length == 0 || variable == "null")
		return true;
	else
		return false;
}

// This utility function builds a basic request for the AJAX components.
function request_builder(value)
{
	return { 'PURPOSE': value,'url': 'ReportBuilder.jsp' };
}

// This utility function builds a request that sends data to the servlet.
function extend_request_builder_with_data(value1,value2,value3)
{
	return {'PURPOSE':value1,'url': 'ReportBuilder.jsp','SECTION':value2, 'DATA':value3};
}

// This utility function puts the report number at the top of the page.
function setting_report_number()
{
	$('#ReportNumber').text('Report #: '+$('#ReportNumber').text());
}
/** End 'Utility' functions section*/

//TODO a section marker between utility functions and 'Display' functions

/** This section contains the functions that display the dynamic lists*/
// This function displays the list of links found in the User Interface Data fold of the accordion.
function displayLinksList()
{
	var string = '<tr >'+
	'<td width="205"><a href="http://www.alaska.gov/" target="_blank">State of Alaska</a> <span style="font-size: 9.5pt">&lt;</span>Cannot Alter<span style="font-size: 9.5pt">&gt;</span></td>'+
	'<td width="115"><button id="create_link" class="ui-button ui-state-default ui-corner-all" onclick="open_link_for_edit(-1);">Create new Link</button></td>'+
	'</tr>';
	for(i=1;i<user_interface.links_list.length;i++)
	{
		string = string+'<tr id="'+(i)+'">';
		string = string+'<td id="1" onclick="open_link_for_edit('+i+');"><a href="' + user_interface.links_list[i].link_address + '" target="_blank">' + user_interface.links_list[i].link_text + '</a></td>' +
				'<td>&nbsp;&nbsp;<button id="delete_link" class="ui-button ui-state-default ui-corner-all" onclick="delete_trail_row('+i+');">Delete this Link</button></td>' +
				'</tr>';
	}
	$('#links_list tbody').html(string);
}

// This function displays the list of field_obj in the fields array, displaying it in the Fields Table fold.
function displayFields()
{
	var string = "";
	for(i=1;i<fields.length;i++)
	{
		fields[i] = new field_obj((i),fields[i].field_name,fields[i].field_display_name,
				fields[i].description,fields[i].field_sortable,fields[i].default_selected,fields[i].field_sort_order,
				fields[i].data_type,fields[i].field_function,fields[i].value_info,fields[i].display);
		
		string = string+'<tr id="'+(i)+'">';
		string = string+'<td id="1" onclick="open_field_for_edit('+(i)+');">' + fields[i].field_number + '</td>' +
				'<td id="2" onclick="open_field_for_edit('+(i)+');">';
		/*if(fields[i].field_name != null && fields[i].field_name.length > 14)
			string += fields[i].field_name.substr(0,14);
		else
			string += fields[i].field_name;*/
		string += maxLength(fields[i].field_name,14);
		string += '</td>' + 
				'<td id="3" onclick="open_field_for_edit('+(i)+');">' + maxLength(fields[i].field_display_name,16) + '</td>' +
				'<td id="4" onclick="open_field_for_edit('+(i)+');">' + fields[i].field_sort_order + '</td>' +
				'<td id="5" onclick="open_field_for_edit('+(i)+');">' + fields[i].data_type + '</td>' +
				'<td onclick="delete_field_row('+fields[i].field_number+');"><c><button id="delete_field" class="ui-button ui-state-default ui-corner-all">Delete</button></c></td>' +
				'</tr>';
	}
	$('#field_list tbody').html(string);
}

//This function displays the list of parameter_obj in the parameters array, displaying it in the 
//		Parameters Table fold.
function displayParameters()
{
	// For some reason, the accordion won't let you set the 
	// column width. This is needed to keep the accordion the same size, so it doesn't suddenly expand when
	// you open the Parameters fold when some of the members have long datastrucutre names.
	var string = "";
	for(n=1;n<parameters.length;n++)
	{
		parameters[n] = new parameter_obj((n),parameters[n].parameter_name,parameters[n].parameter_display_name,
				parameters[n].parameter_description,parameters[n].data_type,parameters[n].parameter_required,parameters[n].actual_values,
				parameters[n].display_values,parameters[n].ds_schema,parameters[n].ds_name,parameters[n].ds_field_names,
				parameters[n].where_clause,parameters[n].order_by_clause,parameters[n].constraining_parameter_name,parameters[n].validator_name);
		string = string+'<tr id="'+(n)+'">';
		string = string+'<td id="1" onclick="open_parameter_for_edit('+(n)+');">' + parameters[n].parameter_number + '</td>';
		string = string+'<td id="2" onclick="open_parameter_for_edit('+(n)+');">';
		string += maxLength(parameters[n].parameter_name,14)+ '</td>';
		string=string+'<td id="3" onclick="open_parameter_for_edit('+n+');">';
		string += maxLength(parameters[n].parameter_display_name,14)+ '</td>';
		string=string+'<td id="4" onclick="open_parameter_for_edit('+n+');">';
		string+=maxLength(parameters[n].ds_name,14)+ '</td>';
		string=string+'<td id="5" onclick="open_parameter_for_edit('+(n)+');">' + parameters[n].data_type + '</td>' +
				'<td onclick="delete_parameter_row('+parameters[n].parameter_number+');"><c><button id="delete_parameter" class="ui-button ui-state-default ui-corner-all">Delete</button></c></td>' +
				'</tr>';
	}
	$('#parameter_list tbody').html(string);
}

//This function displays the list of security_obj in the securitys array, displaying it in the Security 
//	Table fold.
function displaySecuritys()
{
	var string = "";
	for(n=1;n<securitys.length;n++)
	{
		string = string+'<tr>' +
			'<td id="1" id="'+(n)+'" onclick="open_security_for_edit('+(n)+');">' + securitys[n].security_restriction + '</td>' + 
			'<td id="2" id="'+(n)+'" onclick="open_security_for_edit('+(n)+');">' + securitys[n].security_parameters + '</td>' +
			'<td onclick="delete_security_row('+n+');"><c><button id="delete_security" class="ui-button ui-state-default ui-corner-all">Delete</button></c></td>'+
			'</tr>';
	}
	$('#security_list tbody').html(string);
}
/** End the 'Display' functions section */

//TODO a section marker between 'display' functions and 'delete' functions

/** These functions remove a member from their respective dynamically created list. */
// This function deletes the indicated link from the list found in the User Interface Data fold.
function delete_link_in_trail()
{
	temp = user_interface.links_list[0];
	user_interface.links_list.splice(temp,1);
	displayLinksList();
	user_interface.links_list[0] = -1;
}

//This function deletes the indicated member from the list found in the Fields Table fold.
function delete_field()
{
	temp = fields[0];
	fields.splice(temp, 1);
	displayFields();
	fields[0] = -1;
}

//This function deletes the indicated member from the list found in the Parameters Table fold.
function delete_parameter()
{
	temp = parameters[0];
	parameters.splice(temp, 1);
	displayParameters();
	parameters[0] = -1;
}

//This function deletes the indicated member from the list found in the Security Table fold.
function delete_security()
{
	temp = securitys[0];
	securitys.splice(temp, 1);
	securitys[0] = -1;
	displaySecuritys();
}
/** End 'Delete' functions section*/

//TODO a section marker between 'delete' functions and 'sort' functions

/** This section contains the functions that sort the members of the dynamically created lists */
// This function sorts the members of the fields array according to their number
function sortFields()
{
	temp = fields.slice(1);
	
	if(temp != null)
	{
		temp.sort(function(a,b)
		{
			if((a.field_number-b.field_number) == 0)
			{
				if(a.field_name == fields[1].field_name)
					return -1;
				else 
					return 1;
			}
			else
				return a.field_number-b.field_number;
		});
	}
	fields.concat(fields.slice(0,1),temp);
}

//This function sorts the members of the parameters array according to their number
function sortParameters()
{
	temp = parameters.slice(1);
	
	if(temp != null)
		temp.sort(function(a,b)
		{
			if ((a.parameter_number - b.parameter_number) == 0) {
				a.parameter_number++;
				return a.parameter_number - b.parameter_number;
			} else
				return a.parameter_number - b.parameter_number;
		});
	parameters.concat(parameters.slice(0,1),temp);
}
/** End 'Sort' functions section */

//TODO a section marker between 'sort' functions and the 'special' section

/** Special Section just for the dynamically created list of fields in the data source table*/
// This will only get called when the list is initially asked for.
function fillFieldsList()
{
	// This is the row. The idea is to, if there is a list of fields from the data source, change the html so
	// 		instead of being a text box, the input is a select, populated with the list.
	
	if(isNull(ds_fields))
		return false;
	else
	{
		$('#field_name_data').html('<select name="field_name" class="text ui-widget-content ui-corner-all" id="field_name" maxlength="38" onblur="fillFieldsDataTypeList($(this).val(),$(\'#field_data_type\'))"></select>');
		var string = '<option value="null" selected="selected">None&nbsp;</option>';
		for(i = 0;i<ds_fields.length;i++)
		{
			string += '<option value="'+ds_fields[i].name+'">'+ds_fields[i].name+'&nbsp;</option>';
		}
		$('#field_name').html(string);
		
		$('#parameter_name_data').html('<select name="parameter_name" class="text ui-widget-content ui-corner-all" id="parameter_name" maxlength="38" onblur="fillFieldsDataTypeList($(this).val(),$(\'#data_type\'))"></select>');
		string = '<option value="null" selected="selected">None&nbsp;</option>';
		for(i = 0;i<ds_fields.length;i++)
		{
			string += '<option value="'+ds_fields[i].name+'">'+ds_fields[i].name+'&nbsp;</option>';
		}
		$('#parameter_name').html(string);
		return false;
	}
}

// this will only get called when the Edit Function or Edit Parameter windows are open and a function name has been
//		selected. "name" is the name of the field or parameter.  "where" is the HTML object the list is to be placed in.
function fillDataTypeList(name,where)
{
	// The select that contains the data type of the field.  If there is no list of fields from the data source,
	//		leave this alone.  If there is a list, then populate the select according to the type(s) that the 
	//		selected field is/can be; VARCHAR2, NUMBER, DATE, or SDO_GEOMETRY
	
	var string = "";
	var index = 0;
	for(i = 0;i<ds_fields.length;i++)
	{
		if(ds_fields[i].name == name)
		{
			index = i;
		}
	}
	if(ds_fields.length >0)
	{
		if(ds_fields[index].type == "VARCHAR2")
		{
			if(where.attr('id') == 'field_data_type')
			{
				string += '<option value="TEXT" selected="selected">Text&nbsp;</option>';
			}
			else
			{
				string += '<option value="TEXT" selected="selected">Text&nbsp;</option><option value="LIST">List&nbsp;</option><option value="LINK">Link&nbsp;</option><option value="SECTION">Section&nbsp;</option>';
			}
		}
		else if(ds_fields[index].type == "NUMBER")
		{
			string += '<option value="NUMBER" selected="selected">Number&nbsp;</option>';
		}
		else if(ds_fields[index].type == "DATE")
		{
			string +='<option value="DATE" selected="selected">Date&nbsp;</option>';
		}
		else
		{
			string +='<option value="SPATIAL" selected="selected">Spatial&nbsp;</option>';
		}
		
		where.html(string);
		if(where.attr('id') == 'field_data_type')
		{
			if(fields[fields[0]] == undefined)
				where.val("TEXT");
			else
				where.val(fields[(fields[0])].data_type);
		}
		else
		{
			if(parameters[parameters[0]] == undefined)
				where.val("TEXT");
			else
				where.val(parameters[(parameters[0])].data_type);
		}
	}
}
/** End 'Special' functions section*/

// TODO A marker between the 'Special' section and the AJAX section

/** AJAX section */
// create a new f(x) just for the getting of JSON stuff.
function makeJSONrequest(method, url, request, ID) 
{
	$.post(url,request, function(data)
	{
		var returned=data;
		if(returned[0]==$('#ReportNumber').text())
		{
	    	if(ID.text()=='Driver Table')
	    	{
	    		var change = false;
	    		$('#reportName').val(returned[1]);
	    		$('#reportDesc').val(returned[2]);
	    		$('#driverComments').val(returned[3]);
	    		$('#driverActive').val(returned[4]);
	    		$('#byPassed').val(returned[5]);
	    		if(driver.reportSchema != returned[7])
	    		{
	    			change = true;
	    		}
	    		$('#reportSchema').val(returned[7]);
	    		if(driver.reportDS != returned[8])
	    		{
	    			change = true;
	    		}
	    		$('#reportDS').val(returned[8]);
	    		$('#mapName').val(returned[9]);
	    		$('#mapUID').val(returned[10]);
	    		$('#coord_system_name').val(returned[11]);
	    		driver = new driver_obj(returned[1],returned[2],returned[3],returned[4],returned[5],returned[6],returned[7],returned[8],returned[9],returned[10]);
	    		if(!change)
	    		{
	    			driver.schemaChange = false;
	    			driver.dsChange = false
	    		}
	    	}
	    	else if(ID.text()=='User Interface Data')
	    	{
	    		var i = 4;
	    		var n = 0;
	    		var lock = true;
	    		var string = "";
	    		$('#interface_page_title').val(returned[1]);
	    		$('#interface_header_title').val(returned[2]);
	    		$('#interface_sub-header_title').val(returned[3]);
	    		$('#interface_image_address').val(returned[4]);
	    		user_interface = new user_interface_obj(returned[1],returned[2],returned[3],returned[4]);
	    		user_interface.links_list[0] = -1;
	    		while(lock)
	    		{
	    			try
	    			{
	    				i++;
	    				n++;
	    				temp_address = returned[i];
	    				var name = " hi ";
	    				var url = " blah ";
	    				if(returned[i] != null)
	    				{
	    					url = returned[i][0];
	    					name = returned[i][1];
	    				}
	    				
	    				if(url.match(" blah "))
	    					lock = false;
	    				else
	    				{
	    					user_interface.links_list[n] = new links_list_obj(name,url);
	    				}
	    			}
	    			catch(err)
	    			{
	    				lock = false;
	    			}
	    		}
	    		user_interface.links_list[0] = -1;
	    		displayLinksList();
	    	}
	    	else if(ID.text()=='Fields Table')
	    	{
	    		var i = 0;
	    		var lock = true;
	    		var string = "";
	    		while(lock)
	    		{
	    			try
	    			{
	    				i++;
	    				returned_obj = returned[i];
	    				returned2 = returned_obj.field;
	        			
	        			fields[i] = new field_obj(returned_obj.ORDERING,returned2[0],returned2[1],returned2[2],returned2[3],returned2[4],returned2[5],returned2[6],returned2[7],returned2[8],returned2[9],returned2[10]);
	    			}
	    			catch(err)
	    			{
	    				lock = false;
	    			}
	    		}
	    		fields[0] = -1;
	    		displayFields();
	    	}
	    	else if(ID.text()=='Parameters Table')
	    	{
	    		var i = 0;
	    		var lock = true;
	    		var string = "";
	    		while(lock)
	    		{
	    			try
	    			{
	    				i++;
	    				returned_obj = returned[i];
	    				returned2 = returned_obj.parameter;
	        			
	        			parameters[i] = new parameter_obj(returned_obj.ORDERING,returned2[0],returned2[1],returned2[2],returned2[3],returned2[4],returned2[5],returned2[6],returned2[7],returned2[8],returned2[9],returned2[10],returned2[11],returned2[12],returned2[13],returned2[14]);
	        		}
	    			catch(err)
	    			{
	    				parameters[0] = -1;
	    				if(parameters.length > 2)
	    					sortParameters();
	    				displayParameters();
	    				lock = false;
	    			}
	    		}
	    	}
	    	else if(ID.text()=='Security Table')
	    	{
	    		var i = 0;
	    		var lock = true;
	    		while(lock)
	    		{
	    			try
	    			{
	    				i++;
	    				returned2 = returned[i];
	        			securitys[i] = new security_obj(returned2[0],returned2[1]);
	    			}
	    			catch(err)
	    			{
	    				securitys[0] = -1;
	    				displaySecuritys();
	    				lock = false;
	    			}
	    		}
	    	}
	    	else if(ID.text()=='Categories Table')
	    	{
	    		var string = '<select name="category" id="category">';
	    		for(i = 0;i<returned.length-2;i++)
	    		{
	    			string += '<option value="'+i+'">'+returned[i+1]+'</option>';
	    		}
	    		if(returned.length-2 < 1){
	    			$('#pre-category').html('<input type="text" name="category" id="category" size="45"/>');}
	    		else
	    		{
	    			$('#pre-category').html(string+'</select>');
	    			$('#category').val(returned[returned.length-1]);
	    		}
	        }
	    }
		else
		{
			window.location.replace('./Login.jsp');
		}
	},"json");
}

//create a new function just for the sending of JSON stuff.
function makeJSONrequestSave(method, url, request, ID) 
{
    if(ID.text()=='Driver Table')
	{
    	if(isNull(document.getElementById("reportName").value))//$('#reportName').val()))
    	{
    		driver.reportName='null';
    	}
    	else
    	{
    		driver.reportName=$('#reportName').val();
    	}
    	if(isNull($('#reportDesc').val()))
    	{
    		driver.reportDesc='null';
    	}
    	else
    	{
    		driver.reportDesc=$('#reportDesc').val();
    	}
    	if(isNull($('#driverComments').val()))
    	{
    		driver.driverComments='null';
    	}
    	else
    	{
    		driver.driverComments=$('#driverComments').val();
    	}
    	if(isNull($('#driverActive').val()))
    	{
    		driver.driverActive='null';
    	}
    	else
    	{
    		driver.driverActive=$('#driverActive').val();
    	}
    	if(isNull($('#byPassed').val()))
    	{
    		driver.byPassed='null';
    	}
    	else
    	{
    		driver.byPassed=$('#byPassed').val();
    	}
    	if(isNull($('#reportDS').val()))
    	{
    		driver.reportDS='null';
    	}
    	else
    	{
    		if(driver.reportDS != $('#reportDS').val())
    		{
    			driver.dsChange = true;
    		}
    		driver.reportDS=$('#reportDS').val();
    	}
    	if(isNull($('#reportSchema').val()))
    	{
    		driver.reportSchema='null';
    	}
    	else
    	{
    		if(driver.reportSchema != $('#reportSchema').val())
    			driver.schemaChange = true;
    		driver.reportSchema=$('#reportSchema').val();
    	}
    	if(isNull($('#mapName').val()))
    	{
    		driver.mapName='null';
    	}
    	else
    	{
    		driver.mapName=$('#mapName').val();
    	}
    	if(isNull($('#mapUID').val()))
    	{
    	driver.mapUID= 'null';
    	}
    	else
    	{
    		driver.mapUID=$('#mapUID').val();
    	}
    	if(isNull($('#coord_system_name').val()))
    	{
    		driver.coord_system_name='null';
    	}
    	else
    	{
    		driver.coord_system_name=$('#coord_system_name').val();
    	}//*/
    	request=extend_request_builder_with_data('save',ID.text(),JSON.stringify(driver));
	}
    else if(ID.text()=='User Interface Data')
	{
		if(isNull($('#interface_page_title').val()))
		{
			user_interface.interface_page_title='default';
		}
		else
		{
			user_interface.interface_page_title=$('#interface_page_title').val();
		}
		if(isNull($('#interface_header_title').val()))
		{
			user_interface.interface_header_title='default';
		}
		else
		{
			user_interface.interface_header_title=$('#interface_header_title').val();
		}
		if(isNull($('#interface_sub-header_title').val()))
		{
			user_interface.interface_subHeader_title='default';
		}
		else
		{
			user_interface.interface_subHeader_title=$('#interface_sub-header_title').val();
		}
		if(isNull($('#interface_image_address').val()))
		{
			user_interface.interface_image_address='default';
		}
		else
		{
			user_interface.interface_image_address=$('#interface_image_address').val();
		}
		for(i = 1;i<user_interface.links_list.length;i++)
		{
	    	if(isNull(user_interface.links_list[i].link_text))
	    	{
	    		user_interface.links_list[i].link_text='Please report me';
	    	}
	    	if(isNull(user_interface.links_list[i].link_address))
	    	{
	    		user_interface.links_list[i].link_address='http://int.dnr.alaska.gov/ssd/lris/gis/';
	    	}
		}
		request=extend_request_builder_with_data('save',ID.text(),JSON.stringify(user_interface));
	}
    else if(ID.text()=='Fields Table')
	{
    	for(i = 1;i<fields.length;i++)
    	{
	    	if(isNull(fields[i].field_name))
	    	{
	    		fields[i].field_name='null';
	    	}
	    	if(isNull(fields[i].field_display_name))
	    	{
	    		fields[i].field_display_name='null';
	    	}
	    	if(isNull(fields[i].description))
	    	{
	    		fields[i].description='null';
	    	}
	    	if(isNull(fields[i].field_function))
	    	{
	    		fields[i].field_function='null';
	    	}
	    	if(isNull(fields[i].value_info))
	    	{
	    		fields[i].value_info='null';
	    	}
    	}
    	request=extend_request_builder_with_data('save',ID.text(),JSON.stringify(fields));
	}
    else if(ID.text()=='Parameters Table')
	{
    	for(i = 2;i<parameters.length;i++)
    	{
	    	if(isNull(parameters[i].parameter_name))
	    	{
	    		parameters[i].parameter_name='null';
	    	}
	    	if(isNull(parameters[i].parameter_display_name))
	    	{
	    		parameters[i].parameter_display_name='null';
	    	}
	    	if(isNull(parameters[i].parameter_description))
	    	{
	    		parameters[i].parameter_description='null';
	    	}
	    	if(isNull(parameters[i].actual_values))
	    	{
	    		parameters[i].actual_values='null';
	    	}
	    	if(isNull(parameters[i].display_values))
	    	{
	    		parameters[i].display_values='null';
	    	}
	    	if(isNull(parameters[i].ds_name))
	    	{
	    		parameters[i].ds_name='null';
	    	}
	    	if(isNull(parameters[i].ds_field_names))
	    	{
	    		parameters[i].ds_field_names='null';
	    	}
	    	if(isNull(parameters[i].where_clause))
	    	{
	    		parameters[i].where_clause='null';
	    	}
	    	if(isNull(parameters[i].order_by_clause))
	    	{
	    		parameters[i].order_by_clause='null';
	    	}
	    	if(isNull(parameters[i].constraining_parameter_name))
	    	{
	    		parameters[i].constraining_parameter_name='null';
	    	}
    	}
    	request=extend_request_builder_with_data('save',ID.text(),JSON.stringify(parameters));
	}
    else if(ID.text()=='Security Table')
	{
    	for(i = 2;i<securitys[0]+2;i++)
    	{
	    	if(isNull(securitys[i].security_parameters))
	    	{
	    		securitys[i].security_parameters='null';
	    	}
    	}
    	request=extend_request_builder_with_data('save',ID.text(),JSON.stringify(securitys));
	}
    else if(ID.text()=='Categories Table')
	{
    	request=extend_request_builder_with_data('save',ID.text(),$('#category').val());
	}
    $.post(url,request);
}
/** End of the AJAX stuff*/

// TODO the spacer between the AJAX and the User Input section

/** Start of the user input */

/** End of the user input section*/

// TODO a marker between the user input section and the 'fully loaded' section

/** Functions that are to be ran only after the page has been fully loaded*/
$(document).ready(function(){
	
	// These are the variables for the Link Path Creation window
	var	link_address=$('#link_address'),
		link_text=$('#link_text'),
		allLinks = $([]).add(link_address).add(link_text),
		ltips = $("#validateLinkTips");
		
	// These are the variables for the Field Creation Window
	var field_number = $("#field_number"),
		field_name = $("#field_name"),
		field_display_name = $("#field_display_name"),
		field_description = $("#field_description"),
		field_sortable = $('#field_sortable'),
		default_selected= $('#default_selected'),
		field_sort_order = $('#field_sort_order'),
		field_data_type = $('#field_data_type'),
		field_function = $("#field_function"),
		field_value_info = $("#field_value_info"),
		field_display = $('#field_display'),
		allFields = $([]).add(field_number).add(field_name).add(field_display_name).add(field_description).add(field_function).add(field_value_info),
		ftips = $("#validateFieldTips");
		
	// These are the variables for the Parameter Creation Window
	var parameter_number = $("#parameter_number"),
		parameter_name = $("#parameter_name"),
		parameter_display_name = $("#parameter_display_name"),
		parameter_description = $("#parameter_description"),
		parameter_required = $('#parameter_required'),
		data_type = $('#data_type'),
		actual_values = $('#actual_values'),
		display_values = $('#parameter_display_values'),
		ds_schema = $('#ds_schema'),
		ds_name = $('#ds_name'),
		ds_field_names = $('#ds_field_names'),
		where_clause = $('#where_clause'),
		order_by_clause = $('#order_by_clause'),
		constraining_parameter_name = $('#constraining_parameter_name'),
		validator_name = $('#validator_name'),
		allParameters = $([]).add(parameter_number).add(parameter_name).add(parameter_display_name).add(parameter_description).add(actual_values).add(display_values).add(ds_schema).add(ds_name).add(ds_field_names).add(where_clause).add(order_by_clause).add(constraining_parameter_name.add(validator_name)),
		ptips = $("#validateParameterTips");
	
	// These are the variables for the Security Parameter Creation and Editing Window
	var security_row_num = 0,
		security_total_rows = 0,
		security_restriction = $('#security_restriction'),
		security_parameters = $('#security_parameters'),
		allSecurity = $([]).add(security_restriction).add(security_parameters),
		sectips = $('#security_tips');
	
	// These are the variables for the Required Window
	var requiredSchema = $('#requiredSchema'),
		requiredDS = $('#requiredDS'),
		allRequired = $([]).add(requiredSchema).add(requiredDS),
		requiredTips = $('#validateRequiredTips');


	$('#accordion').accordion({ header: "h2",autoHeight: false,collapsible: true,active: false });
	$.ui.dialog.defaults.bgiframe = true;

	// This utility function updates the 'tips' in the pop-up windows.
	function updateTips(t,tips)
	{
		tips.text(t).effect("highlight",{},1500);
	}

	// This utility function checks the string 'o' to see if it is between a certain length.  If it's not,
	// then this function reports this error in the 'tips' secion in the current pop-up window.
	function checkLength(o,n,min,max,tips) 
	{	
		if (isNull(o.val()) && min > 0)
		{
			o.addClass('ui-state-error');
			updateTips("This input must have a value.",tips);
			return false;
		}
		else if (o.val().length > max || o.val().length < min ) 
		{
			o.addClass('ui-state-error');
			updateTips("Length of " + n + " must be between "+min+" and "+max+" characters.",tips);
			return false;
		} else {
			return true;
		}
	}

	// This function fills an empty-length String datastructure.
	function nullLength(n)
	{
		if(n.val().length == 0)
		{
			n.val("null");
			return true;
		}
	}

	// This function checks a given String 'o' over with a regular expression.  If it fits, then the funciton
	// returns true, other wise the function sends the error message 'n' to the 'tips' portion of the pop-up 
	// window and returns false.
	function checkRegexp(o,regexp,n,tips)
	{
		if(!(regexp.test(o.val()))) 
		{
			o.addClass('ui-state-error');
			updateTips(n,tips);
			return false;
		} else {
			return true;
		}
	}
	
	// This is the function to open a window to create a link in the link trail of the report
	$('#link_trail').dialog(
	{
		bgiframe: true,
		autoOpen: false,
		modal: true,
		height: 220,
		width: 600,
		buttons: 
		{
			
			"Cancel": function() 
			{ 
				$(this).dialog("close"); 
			},
			"Ok": function() 
			{ 
				var bValid = true;//*
				allLinks.removeClass('ui-state-error');
			
				bValid = bValid && checkLength(link_text,"Link's Text",1,25,ltips);
				bValid = bValid && checkLength(link_address,"Link's URL",1,100,ltips);
				bValid = bValid && checkRegexp(link_address,/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[A-Z0-9+&@#\/%=~_|]/i,"Not valid link format.",ltips);
				// */
				
				if (bValid)
				{ 
					if(user_interface.links_list[0] == -1)
					{
						user_interface.links_list[(user_interface.links_list.length)]= new links_list_obj(link_text.val(),link_address.val());
					}
					else
					{
						user_interface.links_list[(user_interface.links_list[0])].link_address=link_address.val();
						user_interface.links_list[(user_interface.links_list[0])].link_text=link_text.val();
					}
					
					$(this).dialog("close");
				}				 
			}
		},
		open: function()
		{
			if(user_interface.links_list[0] != -1)
			{
				// this shows where in the array this field is
				links_list_row_num = user_interface.links_list[0];
	
				link_address.val(user_interface.links_list[user_interface.links_list[0]].link_address);
				link_text.val(user_interface.links_list[(user_interface.links_list[0])].link_text);
			}
		},
		close: function()
		{
			allLinks.val('').removeClass('ui-state-error');
			displayLinksList();
			user_interface.links_list[0] = -1;
			ltips.text("All form fields are required.");
		}
	});
	
	// This is the function to open the window to create the fields of the report
	$('#field').dialog(
	{
		bgiframe: true,
		autoOpen: false,
		modal: true,
		height: 615,
		width: 600,
		buttons: 
		{
			
			"Cancel": function() 
			{ 
				$(this).dialog("close"); 
			},
			"Ok": function() 
			{ 
				var bValid = true;
				allFields.removeClass('ui-state-error');
				regexp = /null/i;
				bValid = bValid && checkLength(field_number,"Number",1,2,ftips);
				bValid = bValid && checkRegexp(field_number,/([0-9])+$/i,"This parameter can only be numbers, no letters or punctuation.",ftips);
				bValid = bValid && checkLength($('#field_name'),"Field Name",1,38,ftips);
				bValid = bValid && checkRegexp($('#field_name'),/^[a-zA-Z]([0-9a-z_])+$/i,"Field names may consist of a-z, 0-9, or underscores. They must begin with a letter.",ftips);
				bValid = bValid && checkLength(field_display_name,"Display Name",1,256,ftips);
				bValid = bValid && checkRegexp(field_display_name,/^[a-zA-Z]([0-9a-zA-Z ':])+$/i,"Display names may consist of a-z, 0-9, spaces, a colon, or an apostrophe. They must begin with a letter.",ftips);
				bValid = bValid && (checkLength(field_description,"Description",0,2048,ftips) || nullLength(field_description));
				bValid = bValid && checkLength(field_function,"Display Function",0,256,ftips);
				if(!nullLength(field_function) && !regexp.test(field_function.val()))
				{
					bValid = bValid && checkRegexp(field_function,/^[a-zA-Z]/i,"All SQL functions start with a letter.",ftips);
					bValid = bValid && checkRegexp(field_function,/\(/i,"Missing opening parenthesis.",ftips)&&checkRegexp(field_function,/\)/i,"Missing closing parenthesis.",ftips);
					bValid = bValid && checkRegexp(field_function,/\(([a-zA-Z0-9_]+,)*\?(,[a-zA-Z0-9_]+)*\)/i,"The SQL function must have at least one '?' in its parameters as a place holder for the field name.",ftips);
				}

				bValid = bValid && checkLength(field_value_info,"Value Information",0,2000,ftips);
				if(!nullLength(field_value_info) && !regexp.test(field_value_info.val()))
				{
					bValid = bValid && checkRegexp(field_value_info,/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[A-Z0-9+&@#\/%=~_|]/i,"Not valid link format.",ftips);
				}
				if (bValid)
				{
					if(fields[0] == -1)  
					{
						if(field_number.val() == fields.length)
						{
							fields[(fields.length)]= new field_obj(field_number.val(),$('#field_name').val(),field_display_name.val(),field_description.val(),
									$('#field_sortable').val(),$('#default_selected').val(),
									$('#field_sort_order').val(),$('#field_data_type').val(),
									field_function.val(),field_value_info.val(),$('#field_display').val());
						}
						else
						{
							fields.splice(field_number.val(), 0, new field_obj(field_number.val(),$('#field_name').val(),field_display_name.val(),field_description.val(),
									$('#field_sortable').val(),$('#default_selected').val(),
									$('#field_sort_order').val(),$('#field_data_type').val(),
									field_function.val(),field_value_info.val(),$('#field_display').val()));
						}
					}
					else
					{
						if(field_number.val == fields[(fields[0])].field_number)
						{
							fields[(fields[0])].field_number=field_number.val();
							fields[(fields[0])].field_name=$('#field_name').val();
							fields[(fields[0])].field_display_name=field_display_name.val();
							fields[(fields[0])].description=field_description.val();
							fields[(fields[0])].field_sortable=$('#field_sortable').val();
							fields[(fields[0])].default_selected=$('#default_selected').val();
							fields[(fields[0])].field_sort_order=$('#field_sort_order').val();
							fields[(fields[0])].data_type=$('#field_data_type').val();
							fields[(fields[0])].field_function=field_function.val();
							fields[(fields[0])].value_info=field_value_info.val();
							fields[(fields[0])].display=$('#field_display').val();
						}
						else
						{
							fields.splice(fields[0],1);
							fields.splice(field_number.val(),0,new field_obj(field_number.val(),$('#field_name').val(),field_display_name.val(),field_description.val(),
									$('#field_sortable').val(),$('#default_selected').val(),
									$('#field_sort_order').val(),$('#field_data_type').val(),
									field_function.val(),field_value_info.val(),$('#field_display').val()));
						}
					}
					$(this).dialog("close");
				}				 
			}
		},
		open: function()
		{
			if(fields[0] != -1)
			{
				field_number.val(fields[(fields[0])].field_number);
				$('#field_name').val(fields[(fields[0])].field_name);
				field_display_name.val(fields[(fields[0])].field_display_name);
				field_description.val(fields[(fields[0])].description);
				$('#field_sortable').val(fields[(fields[0])].field_sortable);
				$('#default_selected').val(fields[(fields[0])].default_selected);
				$('#field_sort_order').val(fields[(fields[0])].field_sort_order);
				$('#field_data_type').val(fields[(fields[0])].data_type);
				field_function.val(fields[(fields[0])].field_function);
				field_value_info.val(fields[(fields[0])].value_info);
				$('#field_display').val(fields[(fields[0])].display);
			}
			else
			{
				field_number.val(fields.length);
			}
		},
		close: function()
		{
			sortFields();
			displayFields();
			allFields.val('').removeClass('ui-state-error');
			$('#field_name').removeClass('ui-state-error');
			$('#field_sortable').val('T');
			$('#default_selected').val("T");
			$('#field_sort_order').val("null");
			$('#field_data_type').val("null");
			$('#field_display').val("T");
			$('#field_name').val("null");
			fields[0] = -1;
			ftips.text("No errors.");
		}
	});
	
	$('#create_field').click(function(){
		fields[0]=-1;
		$('#field').dialog('open'); 
		return false;
	});
	
	// This is the function to edit the parameters of the report
	$('#parameter').dialog(
	{
		bgiframe: true,
		autoOpen: false,
		modal: true,
		height: 695,
		width: 600,
		buttons: 
		{
			
			"Cancel": function() 
			{ 
				$(this).dialog("close"); 
			},
			"Ok": function() 
			{ 
				var bValid = true;
				allParameters.removeClass('ui-state-error');
			
				bValid = bValid && checkLength(parameter_number,"Number",1,2,ptips);
				bValid = bValid && checkRegexp(parameter_number,/([0-9])+$/i,"This parameter can only be numbers, no letters or punctuation.",ptips);
				
				bValid = bValid && checkLength($('#parameter_name'),"Parameter Name",1,38,ptips);
				bValid = bValid && checkRegexp($('#parameter_name'),/^[a-z]([0-9a-z_])+$/i,"Parameter names may consist of a-z, 0-9, or underscores. They must begin with a letter.",ptips);
				
				bValid = bValid && checkLength(parameter_display_name,"Display Name",1,256,ptips);
				bValid = bValid && checkRegexp(parameter_display_name,/^[a-z]([0-9a-z ?:])+$/i,"Display names may consist of a-z, 0-9, spaces, a colon, or an apostrophe. They must begin with a letter.",ptips);
				
				bValid = bValid && (checkLength(parameter_description,"Description",0,2048,ptips) || nullLength(field_description));
				
				if (bValid)
				{ 

					if(parameters[0] == -1)
					{
						if(parameter_number.val() == parameters.length)
						{
							parameters[(parameters.length)]= new parameter_obj(parameter_number.val(),$('#parameter_name').val(),parameter_display_name.val(),parameter_description.val(),
									$('#data_type').val(),$('#parameter_required').val(),
									actual_values.val(),display_values.val(),$('#ds_schema').val(),
									ds_name.val(),ds_field_names.val(),where_clause.val(),order_by_clause.val(),constraining_parameter_name.val(),validator_name.val());
						}
						else
						{
							parameters.splice(parameter_number.val(), 0, new parameter_obj(parameter_number.val(),$('#parameter_name').val(),parameter_display_name.val(),parameter_description.val(),
									$('#data_type').val(),$('#parameter_required').val(),
									actual_values.val(),display_values.val(),$('#ds_schema').val(),
									ds_name.val(),ds_field_names.val(),where_clause.val(),order_by_clause.val(),constraining_parameter_name.val(),validator_name.val()));
						}
					}
					else
					{
						if(parameters[(parameters[0])].parameter_number==parameter_number.val())
						{
							parameters[(parameters[0])].parameter_number=parameter_number.val();
							parameters[(parameters[0])].parameter_name=$('#parameter_name').val();
							parameters[(parameters[0])].parameter_display_name=parameter_display_name.val();
							parameters[(parameters[0])].parameter_description=parameter_description.val();
							parameters[(parameters[0])].data_type=$('#data_type').val();
							parameters[(parameters[0])].parameter_required=$('#parameter_required').val();
							parameters[(parameters[0])].actual_values=actual_values.val();
							parameters[(parameters[0])].display_values=display_values.val();
							parameters[(parameters[0])].ds_schema=$('#ds_schema').val();
							parameters[(parameters[0])].ds_name=ds_name.val();
							parameters[(parameters[0])].ds_field_names=ds_field_names.val();
							parameters[(parameters[0])].where_clause=where_clause.val();
							parameters[(parameters[0])].order_by_clause=order_by_clause.val();
							parameters[(parameters[0])].constraining_parameter_name=constraining_parameter_name.val();
							parameters[(parameters[0])].validator_name=validator_name.val();
						}
						else
						{
							parameters.splice(parameters[0], 1);
							parameters.splice(parameter_number.val(),0,new parameter_obj(parameter_number.val(),$('#parameter_name').val(),parameter_display_name.val(),parameter_description.val(),
									$('#data_type').val(),$('#parameter_required').val(),
									actual_values.val(),display_values.val(),$('#ds_schema').val(),
									ds_name.val(),ds_field_names.val(),where_clause.val(),order_by_clause.val(),constraining_parameter_name.val(),validator_name.val()));
						}
						var i = parameters[0];
					}
					$(this).dialog("close");
				}				 
			}
		},
		open: function()
		{var string = "";
			if(parameters[0] != -1)
			{
				parameter_number.val(parameters[(parameters[0])].parameter_number);
				$('#parameter_name').val(parameters[(parameters[0])].parameter_name);
				parameter_display_name.val(parameters[(parameters[0])].parameter_display_name);
				parameter_description.val(parameters[(parameters[0])].parameter_description);
				$('#data_type').val(parameters[(parameters[0])].data_type);
				$('#parameter_required').val(parameters[(parameters[0])].parameter_required);
				actual_values.val(parameters[(parameters[0])].actual_values);
				display_values.val(parameters[(parameters[0])].display_values);
				$('#ds_schema').val(parameters[(parameters[0])].ds_schema);
				ds_name.val(parameters[(parameters[0])].ds_name);
				ds_field_names.val(parameters[(parameters[0])].ds_field_names);
				where_clause.val(parameters[(parameters[0])].where_clause);
				order_by_clause.val(parameters[(parameters[0])].order_by_clause);
				
				string = '<option value="null" selected="selected">None&nbsp;</option>';
				for(j = 1;j < parameters.length;j++)
				{
					if(j != parameters[0])
						string += '<option value="'+parameters[j].parameter_name+'">'+parameters[j].parameter_name+'&nbsp;</option>';
				}
				constraining_parameter_name.html(string);
				constraining_parameter_name.val(parameters[(parameters[0])].constraining_parameter_name);
				validator_name.val(parameters[(parameters[0])].validator_name);
			}
			else
			{
				parameter_number.val(parameters.length);
				string = '<option value="null" selected="selected">None&nbsp;</option>';
				for(j = 1;j < parameters.length;j++)
				{
					string += '<option value="'+parameters[j].parameter_name+'">'+parameters[j].parameter_name+'&nbsp;</option>';
				}
				constraining_parameter_name.html(string);
				validator_name.val('');
			}
		},
		close: function()
		{
			sortParameters();
			displayParameters();
			allParameters.val('').removeClass('ui-state-error');
			$('#data_type').val('null');
			$('#parameter_required').val('F');
			$('#ds_schema').val('null');
			$('#parameter_name').val("null").removeClass('ui-state-error');
			constraining_parameter_name.val('null');
			parameters[0] = -1;
		}
	});
	
	$('#create_parameter').click(function(){
		$('#parameter').dialog('open');
		return false;
	});
	
	// This is the function to edit the parameters of the report
	$('#security').dialog(
	{
		bgiframe: true,
		autoOpen: false,
		modal: true,
		height: 205,
		width: 800,
		buttons: 
		{
			
			"Cancel": function() 
			{ 
				$(this).dialog("close"); 
			},
			"Ok": function() 
			{ 
				var bValid = true;
				allSecurity.removeClass('ui-state-error');
			
				if(security_restriction.val() == 'PUBLIC')
					bValid = bValid && checkLength(security_parameters,"Security Parameters",0,200,sectips);
				else if(security_restriction.val() == 'INDIVIDUAL')
				{
					bValid = bValid && checkLength(security_parameters,"Security Parameters",1,200,sectips);
					bValid = bValid && checkRegexp(security_parameters,/^[a-zA-Z-]+(, [a-zA-Z-]+)*$/i,"Individuals names can only have letters or a '-' sign.  They are deliniated by ', '",sectips);
				}
				else if(security_restriction.val() == 'GROUP')
				{
					bValid = bValid && checkLength(security_parameters,"Security Parameters",1,200,sectips);
					bValid = bValid && checkRegexp(security_parameters,/^[a-zA-Z\.]+( [a-zA-Z\.]+)*$/i,"Group names can only have letters and the '.'  They are deliniated by a space.",sectips);
				}
				else if(security_restriction.val() == 'ATTRIBUTE')
				{
					bValid = bValid && checkLength(security_parameters,"Security Parameters",1,200,sectips);
				}
				else
					bValid = false;
				
				if (bValid)
				{ 
					if(securitys[0] == -1)
					{
						securitys[securitys.length] = new security_obj(security_restriction.val(),security_parameters.val());
					}
					else
					{
						securitys[securitys[0]]=new security_obj(security_restriction.val(),security_parameters.val());
					}
					$(this).dialog("close");
				}				 
			}
		},
		open: function()
		{
			if(securitys[0] != -1)
			{	
				security_restriction.val(securitys[(securitys[0])].security_restriction);
				security_parameters.val(securitys[(securitys[0])].security_parameters);
			}
		},
		close: function()
		{
			displaySecuritys();
			allSecurity.val('').removeClass('ui-state-error');
			securitys[0] = -1;
			$('#security_restriction').val('PUBLIC');
		}
	});
	
	$('#create_security_parameter').click(function(){
		$('#security').dialog('open');
		return false;
	});
	
	$('#required').dialog(
	{
		bgiframe: true,
		autoOpen: false,
		modal: true,
		height: 205,
		width: 800,
		buttons: 
		{
			"Cancel": function() 
			{ 
				$(this).dialog("close"); 
			},
			"Send to server": function() 
			{ 
				if(requiredSchema.val().length > 0 && requiredDS.val().length > 0)
				{
					var tempArray = new Array();
					tempArray[0] = requiredSchema.val();
					tempArray[1] = requiredDS.val();
					
					request=extend_request_builder_with_data("load","Field Names and Types",
							JSON.stringify(tempArray));
					$.post("List",request, function(data)
					{
						if(isNull(data.length))
						{
							updateTips("The Schema and/or Datasource you typed in is invalid.",requiredTips);
							ds_fields = new Array();
						}
						else
						{
							// Since the report schema is being used for getting the valid field names,
							// the flag indicating that the schema has been changed get's set to false.
							$('#reportSchema').val(ds_fields[0]);
							driver.reportSchema = ds_fields[0];
							driver.schemaChange = false;
							
							// The same goes for the report's datastructure.
							$('#reportDS').val(ds_fields[1]);
							driver.reportDS = ds_fields[1];
							driver.dsChange = false;
							
							ds_fields = new Array();
							for(i = 0;i<data.length;i++)
							{
								ds_fields[i] = new ds_field_obj(data[i][0],data[i][1]);
							}
							
							$('#required').dialog("close");
						}
					},"json");
				}
				else
				{
					if(requiredSchema.val().length == 0)
						requiredSchema.addClass('ui-state-error');
					if(requiredDS.val().length == 0)
						requiredDS.addClass('ui-state-error');
					
					updateTips("There are still errors in the fields.",requiredTips);
				}
			}
		},
		open:function()
		{
			requiredSchema.val(driver.reportSchema);
			requiredDS.val(driver.reportDS);
			requiredTips.text('All form fields are required.');
		},
		close:function()
		{
			fillFieldsList();
			allRequired.val('').removeClass('ui-state-error');
		}
	});
	
	function getRequired()
	{
		$('#required').dialog('open');
		return false;
	}
	
	$('#scriptWindow').dialog(
	{
		bgiframe: true,
		autoOpen: false,
		modal: true,
		height: 800,
		width: 800,
		buttons: 
		{
			"Close": function() 
			{ 
				$(this).dialog("close"); 
			}
		},
		open:function()
		{
			var temp = $('#hiddenText').text();
			$('#script').val(temp);
		}
	});
	
	$("#hiddenWindow").dialog(
	{
		autoOpen:false
	});
	
	// This utility function builds a slightly more complex request for the AJAX components, usually
	// to request the servlet to send data to be displayed on the page.
	function extend_request_builder(value1,value2)
	{
		return {'PURPOSE':value1,'url': 'ReportBuilder.jsp','SECTION':value2};
	}
	
	$('.ui-accordion').bind('accordionchangestart', function(event, ui)
	{		
		if(ui.oldHeader.html() != null)
		{
			var request=extend_request_builder("save",ui.oldHeader.text());
			makeJSONrequestSave("POST", "List", request,ui.oldHeader);
		} 
		
		if(ui.newHeader.html() != null)
		{
			var request=extend_request_builder("load",ui.newHeader.text());
			makeJSONrequest("POST", "List", request,ui.newHeader);
		}
		if((ui.newHeader.text() == "Fields Table" || ui.newHeader.text() == "Parameters Table")&&(driver.dsChange || driver.schemaChage))
		{		
			var request=extend_request_builder("load","Field Names and Types");
			$.post("List",request, function(data)
			{
				if(isNull(data))
				{
					getRequired();
				}
				else
				{
					for(i = 0;i<data.length;i++)
					{
						ds_fields[i] = new ds_field_obj(data[i][0],data[i][1]);
					}
					driver.dsChange = false;
					driver.schemaChange = false;
					fillFieldsList();
				}
			},"json");
		}
	});
	
	// This is the function that fires when the user tries to move away from the Report Builder page.
	window.onbeforeunload= function (evt) 
	{	var waiting = true;
        var message = "Warning: You are navigating away from the DBRS Report Builder main page.  Unless you leave by " +
        		"pressing the 'Log Out' or the 'Create/Edit New Report' buttons, this could cause some instability in " +
        		"the links to the Dev database.";
        
    	//*
    	if (typeof evt == 'undefined') 
    	{
    		evt = window.event || e;
    	}
    	if (evt) 
    	{
			evt.returnValue = message;	
		}//*/
		//If the following statement is activated, data will be lost when the user leaves the page.
		//It should only be activated it there is a problem with too many links active in Dev.
		//This has happened only once, so not sure if the testing of the DBRS Report Builder was 
		//the cause.  If it is, activate the following line of script.
		//$.post("List",request_builder("close"),"text");
	};
	
	// This is the function that fires when the 'Commit Report to Database' button is clicked
	$('#commit').click(function()
	{
		var request=request_builder("commit");
		makeJSONrequest("POST", "List", request);
	});
	
	// This is the function that fires when the 'Generate Report's Script' button is clicked
	$('#getScript').click(function()
	{
		var request=request_builder("getScript");
		$.post("List",request, function(data)
		{
			$('#hiddenText').text(data);
			$('#scriptWindow').dialog('open');
		});
	});
	
	// This is the function that fires when the 'Log Out of Report Builder' button is clicked
	$('#logout').click(function()
	{
		$.post('List',request_builder('logout'),function()
		{
			window.location.replace('./Login.jsp');
		});
	});
	
	// This is the function that fires when the 'Create/Edit New Report' button is clicked
	$('#change').click(function()
	{
		window.location.replace("./ChooseReport.jsp");
	});
});